// AppHomeCompose.kt
package com.tencent.compose.sample

import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlin.random.Random
import kotlinx.coroutines.launch
import kotlinx.coroutines.yield
import androidx.compose.foundation.Image
import androidx.compose.material.Button
import androidx.compose.material.Divider
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.ui.layout.ContentScale
// 如果你的 rememberLocalImage 与 Res 在别的包，请改成对应包名
import com.tencent.compose.sample.rememberLocalImage
import composesample.composeapp.generated.resources.Res
//import composesample.composeapp.generated.resources.cat1
//import composesample.composeapp.generated.resources.cat2
import composesample.composeapp.generated.resources.image_cat
import composesample.composeapp.generated.resources.image_dog
import org.jetbrains.compose.resources.ExperimentalResourceApi

/**
 * Single-file Compose implementation of:
 *  - Home with top tabs (Follow/Trend)
 *  - Follow feed list with refresh & load more
 *  - Trending with nested tabs (Recommend / Nearby / ...)
 *
 * Focused on UI only; replace placeholders (images, real data) as needed.
 */

/* ------------------------------
   Top-level screen
   ------------------------------ */
@Composable
internal fun AppHomeScreen(
    modifier: Modifier = Modifier,
    onSettingsClick: () -> Unit = {}
) {
    val resFollow = "关注"
    val resTrend = "热门"
    val titles = listOf(resFollow, resTrend)
    var currentIndex by remember { mutableStateOf(0) }

    Column(modifier = modifier.fillMaxSize()) {
        TopTabs(
            titles = titles,
            selectedIndex = currentIndex,
            onTabSelected = { idx -> currentIndex = idx },
            onSettingsClick = onSettingsClick
        )
        Box(modifier = Modifier.fillMaxSize()) {
            when (currentIndex) {
                0 -> FeedListPage(pageType = "follow")
                else -> TrendingPage()
            }
        }
    }
}
@Composable
private fun TopTabs(
    titles: List<String>,
    selectedIndex: Int,
    onTabSelected: (Int) -> Unit,
    onSettingsClick: () -> Unit
) {
    val background = Color(0xFFF7F7F7)
    val textFocused = Color(0xFF111111)
    val textUnfocused = Color(0xFF888888)
    val indicatorColor = Color(0xFFFF3B30)
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(56.dp)
            .background(background)
            .padding(horizontal = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Row(
            modifier = Modifier.weight(1f),
            verticalAlignment = Alignment.CenterVertically
        ) {
            titles.forEachIndexed { i, title ->
                val selected = i == selectedIndex
                val textColor by animateColorAsState(if (selected) textFocused else textUnfocused)
                Column(
                    modifier = Modifier
                        .padding(horizontal = 10.dp)
                        .clickable { onTabSelected(i) },
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = title,
                        fontSize = 17.sp,
                        fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,
                        color = textColor
                    )
                    Spacer(modifier = Modifier.height(6.dp))
                    Box(
                        modifier = Modifier
                            .height(3.dp)
                            .widthIn(min = 24.dp)
                    ) {
                        if (selected) {
                            Box(
                                modifier = Modifier
                                    .height(3.dp)
                                    .fillMaxWidth()
                                    .background(indicatorColor)
                            )
                        }
                    }
                }
            }
        }

        IconButton(onClick = onSettingsClick) {
            Box(
                modifier = Modifier
                    .size(22.dp)
                    .clip(CircleShape)
                    .background(Color(0xFFAAC7FF))
            )
        }
    }
}

@Composable
internal fun FeedListPage(pageType: String) {
    var isRefreshing by remember { mutableStateOf(false) }
    var isLoadingMore by remember { mutableStateOf(false) }
    val listState = rememberLazyListState()
    val items = remember { mutableStateListOf<FeedItemModel>() }
    val coroutineScope = rememberCoroutineScope()

    LaunchedEffect(pageType) {
        items.clear()
        items.addAll(generateSampleFeeds(start = 0, count = 100))
    }

    LaunchedEffect(listState) {
        snapshotFlow {
            val last = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index
            last
        }.map { it ?: -1 }
            .distinctUntilChanged()
            .filter { idx -> idx >= 0 }
            .collectLatest { lastIndex ->
                val total = items.size
                if (lastIndex >= total - 3 && !isLoadingMore) {
                    isLoadingMore = true
                    delay(700)
                    val newItems = generateSampleFeeds(start = items.size, count = 20)
                    if (newItems.isNotEmpty()) {
                        items.addAll(newItems)
                    }
                    isLoadingMore = false
                }
            }
    }

    Column(modifier = Modifier.fillMaxSize()) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 12.dp, vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Button(onClick = {
                if (!isRefreshing) {
                    isRefreshing = true
                    coroutineScope.launch {
                        delay(800)
                        items.clear()
                        items.addAll(generateSampleFeeds(start = 0, count = 100))
                        isRefreshing = false
                        yield()
                    }
                }
            }) {
                Text(text = if (isRefreshing) "正在刷新..." else "刷新")
            }
            Spacer(modifier = Modifier.width(12.dp))
            Text(text = "共 ${items.size} 条", color = Color(0xFF666666))
        }
        Divider(color = Color(0xFFECECEC))
        LazyColumn(
            modifier = Modifier.fillMaxSize(),
            state = listState,
            contentPadding = PaddingValues(vertical = 8.dp)
        ) {
            items(items, key = { it.id }) { item ->
                FeedCard(item = item)
            }
            item {
                Spacer(modifier = Modifier.height(8.dp))
                if (isLoadingMore) {
                    Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
                        Text(text = "加载中...", color = Color(0xFF777777))
                    }
                } else {
                    Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
                        Text(text = "上滑加载更多", color = Color(0xFFAAAAAA))
                    }
                }
                Spacer(modifier = Modifier.height(16.dp))
            }
        }
    }
}

@Composable
internal fun TrendingPage() {
    val types = listOf(
        "推荐", "附近", "榜单", "明星", "搞笑", "社会", "测试"
    )
    var selected by remember { mutableStateOf(0) }

    Column(modifier = Modifier.fillMaxSize()) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color(0xFFF2F2F2))
                .padding(vertical = 6.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            val density = LocalDensity.current
            types.forEachIndexed { i, t ->
                val selectedColor by animateColorAsState(if (i == selected) Color.Black else Color(0xFF777777))
                Text(
                    text = t,
                    modifier = Modifier
                        .padding(horizontal = 12.dp, vertical = 8.dp)
                        .clickable { selected = i },
                    color = selectedColor,
                    fontSize = 15.sp
                )
            }
        }
        Box(modifier = Modifier.fillMaxSize()) {
            when (selected) {
                0 -> FeedListPage(pageType = "recommend")
                1 -> FeedListPage(pageType = "nearby")
                else -> FeedListPage(pageType = "other_$selected")
            }
        }
    }
}
private data class FeedItemModel(
    val id: String,
    val nick: String,
    val content: String
)
private fun generateSampleFeeds(start: Int, count: Int): List<FeedItemModel> {
    return (start until start + count).map {
        FeedItemModel(
            id = it.toString(),
            nick = "用户_$it",
            content = "这是示例内容（$it），用于展示 Feed 列表。随机一句话：${sampleSentence()}"
        )
    }
}
private fun sampleSentence(): String {
    val samples = listOf(
        "今天天气不错。",
        "刚刚吃了个好吃的午餐。",
        "去看了一场电影，推荐！",
        "学习 Compose 中……",
        "这是一个示例条目。",
        "音乐让人放松。"
    )
    return samples[Random.nextInt(samples.size)]
}
@OptIn(ExperimentalResourceApi::class)
@Composable
private fun FeedCard(item: FeedItemModel) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 12.dp, vertical = 8.dp)
            .background(Color.White)
            .padding(12.dp)
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Avatar(size = 40.dp)
            Spacer(modifier = Modifier.width(8.dp))
            Column {
                Text(text = item.nick, fontWeight = FontWeight.SemiBold, fontSize = 15.sp)
                Spacer(modifier = Modifier.height(4.dp))
                Text(text = "来自 · 手机", color = Color(0xFF777777), fontSize = 12.sp)
            }
        }
        Spacer(modifier = Modifier.height(8.dp))
        Text(text = item.content, fontSize = 14.sp, color = Color(0xFF222222))
        Spacer(modifier = Modifier.height(8.dp))
        Row(modifier = Modifier.fillMaxWidth()) {
            Image(
                bitmap = rememberLocalImage(Res.drawable.image_cat),
                contentDescription = null,
                modifier = Modifier
                    .weight(1f)
                    .height(160.dp),
                contentScale = ContentScale.Crop
            )
            Spacer(modifier = Modifier.width(8.dp))
            Image(
                bitmap = rememberLocalImage(Res.drawable.image_dog),
                contentDescription = null,
                modifier = Modifier
                    .weight(1f)
                    .height(160.dp),
                contentScale = ContentScale.Crop
            )
        }
        Spacer(modifier = Modifier.height(8.dp))

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(text = "转发 12", fontSize = 12.sp, color = Color(0xFF666666))
            Text(text = "评论 34", fontSize = 12.sp, color = Color(0xFF666666))
            Text(text = "点赞 56", fontSize = 12.sp, color = Color(0xFF666666))
        }
    }
}
@Composable
private fun Avatar(size: androidx.compose.ui.unit.Dp) {
    Box(
        modifier = Modifier
            .size(size)
            .clip(CircleShape)
            .background(Color(0xFFCCCCCC))
    )
}
@Composable
internal fun AppHomePreview() {
    MaterialTheme {
        AppHomeScreen(modifier = Modifier.fillMaxSize())
    }
}
